<template>
  <div class="rich-text-editor">
    <!-- 工具栏 -->
    <div class="editor-toolbar">
      <!-- 基础格式工具栏 -->
      <div class="toolbar-section">
        <el-button-group>
          <el-button 
            size="small" 
            @click="formatText('bold')" 
            title="加粗"
            :type="formatStates.bold ? 'primary' : 'default'"
          >
            <strong>B</strong>
          </el-button>
          <el-button 
            size="small" 
            @click="formatText('italic')" 
            title="斜体"
            :type="formatStates.italic ? 'primary' : 'default'"
          >
            <em>I</em>
          </el-button>
          <el-button 
            size="small" 
            @click="formatText('underline')" 
            title="下划线"
            :type="formatStates.underline ? 'primary' : 'default'"
          >
            <u>U</u>
          </el-button>
          <el-button 
            size="small" 
            @click="formatText('strikeThrough')" 
            title="删除线"
            :type="formatStates.strikeThrough ? 'primary' : 'default'"
          >
            <s>S</s>
          </el-button>
        </el-button-group>
        <el-divider direction="vertical" />
        <el-button-group>
          <el-button 
            size="small" 
            @click="formatText('insertUnorderedList')" 
            title="无序列表"
            :type="formatStates.unorderedList ? 'primary' : 'default'"
          >
            <el-icon><List /></el-icon>
          </el-button>
          <el-button 
            size="small" 
            @click="formatText('insertOrderedList')" 
            title="有序列表"
            :type="formatStates.orderedList ? 'primary' : 'default'"
          >
            <span style="font-size: 12px;">#</span>
          </el-button>
          <el-button 
            size="small" 
            @click="formatText('outdent')" 
            title="减少缩进"
          >
            <el-icon><Back /></el-icon>
          </el-button>
          <el-button 
            size="small" 
            @click="formatText('indent')" 
            title="增加缩进"
          >
            <el-icon><Right /></el-icon>
          </el-button>
        </el-button-group>
      </div>
      <el-divider direction="vertical" />
      <!-- 对齐工具栏 -->
      <div class="toolbar-section">
        <el-button-group>
          <el-button 
            size="small" 
            @click="formatText('justifyLeft')" 
            title="左对齐"
            :type="formatStates.justifyLeft ? 'primary' : 'default'"
          >
            <span style="font-size: 12px;">左</span>
          </el-button>
          <el-button 
            size="small" 
            @click="formatText('justifyCenter')" 
            title="居中对齐"
            :type="formatStates.justifyCenter ? 'primary' : 'default'"
          >
            <span style="font-size: 12px;">中</span>
          </el-button>
          <el-button 
            size="small" 
            @click="formatText('justifyRight')" 
            title="右对齐"
            :type="formatStates.justifyRight ? 'primary' : 'default'"
          >
            <span style="font-size: 12px;">右</span>
          </el-button>
          <el-button 
            size="small" 
            @click="formatText('justifyFull')" 
            title="两端对齐"
            :type="formatStates.justifyFull ? 'primary' : 'default'"
          >
            <span style="font-size: 12px;">两</span>
          </el-button>
        </el-button-group>
      </div>
      <el-divider direction="vertical" />
      <!-- 标题工具栏 -->
      <div class="toolbar-section">
        <el-select 
          v-model="selectedFormatBlock" 
          size="small" 
          @change="handleFormatBlockChange"
          placeholder="格式"
          style="width: 100px"
        >
          <el-option label="正文" value="p" />
          <el-option label="标题1" value="h1" />
          <el-option label="标题2" value="h2" />
          <el-option label="标题3" value="h3" />
          <el-option label="标题4" value="h4" />
          <el-option label="引用" value="blockquote" />
          <el-option label="代码块" value="pre" />
        </el-select>
      </div>
      <el-divider direction="vertical" />
      <!-- 颜色和字体工具栏 -->
      <div class="toolbar-section">
        <el-button-group>
          <el-popover
            placement="bottom"
            :width="200"
            trigger="click"
            popper-class="color-picker-popover"
          >
            <template #reference>
              <el-button size="small" title="文字颜色">
                <el-icon><Brush /></el-icon>
              </el-button>
            </template>
            <div class="color-picker">
              <div class="color-options">
                <div
                  v-for="color in textColors"
                  :key="color"
                  class="color-item"
                  :style="{ backgroundColor: color }"
                  :class="{ active: currentForeColor === color }"
                  @click="setForeColor(color)"
                  :title="color"
                />
              </div>
              <el-color-picker
                v-model="customForeColor"
                @change="setForeColor"
                show-alpha
                size="small"
                style="margin-top: 12px; width: 100%;"
              />
            </div>
          </el-popover>
          <el-popover
            placement="bottom"
            :width="200"
            trigger="click"
            popper-class="color-picker-popover"
          >
            <template #reference>
              <el-button size="small" title="背景颜色">
                <el-icon><BrushFilled /></el-icon>
              </el-button>
            </template>
            <div class="color-picker">
              <div class="color-options">
                <div
                  v-for="color in bgColors"
                  :key="color"
                  class="color-item"
                  :style="{ backgroundColor: color }"
                  :class="{ active: currentBackColor === color }"
                  @click="setBackColor(color)"
                  :title="color"
                />
              </div>
              <el-color-picker
                v-model="customBackColor"
                @change="setBackColor"
                show-alpha
                size="small"
                style="margin-top: 12px; width: 100%;"
              />
            </div>
          </el-popover>
        </el-button-group>
        <el-divider direction="vertical" />
        <el-select
          v-model="selectedFontSize"
          size="small"
          @change="handleFontSizeChange"
          placeholder="字号"
          style="width: 80px"
        >
          <el-option label="12px" value="12px" />
          <el-option label="14px" value="14px" />
          <el-option label="16px" value="16px" />
          <el-option label="18px" value="18px" />
          <el-option label="20px" value="20px" />
          <el-option label="24px" value="24px" />
          <el-option label="28px" value="28px" />
          <el-option label="32px" value="32px" />
          <el-option label="36px" value="36px" />
        </el-select>
        <el-select
          v-model="selectedFontFamily"
          size="small"
          @change="handleFontFamilyChange"
          placeholder="字体"
          style="width: 120px"
        >
          <el-option label="默认" value="" />
          <el-option label="宋体" value="SimSun, serif" />
          <el-option label="黑体" value="SimHei, sans-serif" />
          <el-option label="微软雅黑" value="Microsoft YaHei, sans-serif" />
          <el-option label="Arial" value="Arial, sans-serif" />
          <el-option label="Times New Roman" value="Times New Roman, serif" />
          <el-option label="Courier New" value="Courier New, monospace" />
          <el-option label="Consolas" value="Consolas, monospace" />
        </el-select>
      </div>
      <el-divider direction="vertical" />
      <!-- 高级功能工具栏 -->
      <div class="toolbar-section">
        <el-button-group>
          <el-button size="small" @click="insertLink" title="插入链接 (Ctrl+K)">
            <el-icon><Link /></el-icon>
          </el-button>
          <el-button size="small" @click="insertImage" title="插入图片 (Ctrl+Shift+I)">
            <el-icon><Picture /></el-icon>
          </el-button>
          <el-button size="small" @click="insertTable" title="插入表格">
            <el-icon><Grid /></el-icon>
          </el-button>
          <el-button size="small" @click="insertCode" title="插入代码块">
            <span style="font-size: 12px;">代码</span>
          </el-button>
          <el-button size="small" @click="insertHorizontalRule" title="插入分割线">
            <span style="font-size: 12px;">─</span>
          </el-button>
          <el-button size="small" @click="clearFormat" title="清除格式 (Ctrl+\\">
            <el-icon><Refresh /></el-icon>
          </el-button>
        </el-button-group>
      </div>
      <el-divider direction="vertical" />
      <!-- 撤销重做工具栏 -->
      <div class="toolbar-section">
        <el-button-group>
          <el-button size="small" @click="formatText('undo')" title="撤销">
            <el-icon><RefreshLeft /></el-icon>
          </el-button>
          <el-button size="small" @click="formatText('redo')" title="重做">
            <el-icon><RefreshRight /></el-icon>
          </el-button>
        </el-button-group>
      </div>
    </div>

    <!-- 编辑区域 -->
    <div 
      ref="editorRef" 
      class="editor-content"
      :class="{ 'is-focused': isFocused, 'drag-over': isDragOver }"
      contenteditable
      @input="handleInput"
      @paste="handlePaste"
      @drop="handleDrop"
      @dragover.prevent="handleDragOver"
      @dragleave="handleDragLeave"
      @dragend="isDragOver = false"
      @keydown="handleKeyDown"
      @focus="handleFocus"
      @blur="handleBlur"
      :data-placeholder="computedPlaceholder"
      :style="editorStyle"
    ></div>

    <!-- 字数统计（可选） -->
    <div v-if="showWordCount" class="editor-footer">
      <span class="word-count">字数：{{ wordCount }}</span>
    </div>

    <!-- 插入图片对话框 -->
    <el-dialog 
      v-model="imageDialogVisible" 
      title="插入图片" 
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form :model="imageForm">
        <el-form-item label="图片URL">
          <el-input 
            v-model="imageForm.url" 
            placeholder="请输入图片URL"
          />
        </el-form-item>
        <el-form-item label="图片描述">
          <el-input 
            v-model="imageForm.alt" 
            placeholder="请输入图片描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="imageDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmInsertImage">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 插入链接对话框 -->
    <el-dialog 
      v-model="linkDialogVisible" 
      title="插入链接" 
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form :model="linkForm">
        <el-form-item label="链接URL">
          <el-input 
            v-model="linkForm.url" 
            placeholder="请输入链接URL"
          />
        </el-form-item>
        <el-form-item label="链接文本">
          <el-input 
            v-model="linkForm.text" 
            placeholder="请输入链接文本"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="linkDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmInsertLink">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 表格插入对话框 -->
    <el-dialog 
      v-model="tableDialogVisible" 
      title="插入表格" 
      width="300px"
      :close-on-click-modal="false"
    >
      <el-form :model="tableForm">
        <el-form-item label="行数">
          <el-input-number 
            v-model="tableForm.rows" 
            :min="1" 
            :max="20" 
            :step="1"
          />
        </el-form-item>
        <el-form-item label="列数">
          <el-input-number 
            v-model="tableForm.cols" 
            :min="1" 
            :max="10" 
            :step="1"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="tableDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmInsertTable">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 代码插入对话框 -->
    <el-dialog 
      v-model="codeDialogVisible" 
      title="插入代码" 
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="codeForm">
        <el-form-item label="编程语言">
          <el-select 
            v-model="codeForm.language" 
            placeholder="选择编程语言"
            style="width: 100%"
          >
            <el-option label="JavaScript" value="javascript" />
            <el-option label="TypeScript" value="typescript" />
            <el-option label="HTML" value="html" />
            <el-option label="CSS" value="css" />
            <el-option label="Python" value="python" />
            <el-option label="Java" value="java" />
            <el-option label="C++" value="cpp" />
            <el-option label="JSON" value="json" />
            <el-option label="SQL" value="sql" />
            <el-option label="纯文本" value="text" />
          </el-select>
        </el-form-item>
        <el-form-item label="代码内容">
          <el-input 
            v-model="codeForm.code" 
            type="textarea" 
            :rows="10" 
            placeholder="请输入代码内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="codeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmInsertCode">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  List, Link, Picture, Refresh, Grid, RefreshLeft, RefreshRight,
  Brush, BrushFilled, Back, Right
} from '@element-plus/icons-vue'

// Props
const props = defineProps<{
  modelValue?: string
  placeholder?: string
  disabled?: boolean
  minHeight?: string | number
  maxHeight?: string | number
  // 图片上传配置
  imageUploadConfig?: {
    // 是否自动上传
    autoUpload?: boolean
    // 上传前的处理函数
    beforeUpload?: (file: File) => Promise<string> | string
    // 最大图片大小（字节）
    maxSize?: number
    // 支持的图片类型
    accept?: string[]
  }
  // 是否显示字数统计
  showWordCount?: boolean
  // 是否启用工具栏折叠
  collapsibleToolbar?: boolean
}>()

// 计算属性，用于CSS v-bind
const minHeight = computed(() => {
  return props.minHeight || 200
})

const maxHeight = computed(() => {
  return props.maxHeight || 400
})

// Emits
const emit = defineEmits<{
  (e: 'update:modelValue', value: string): void
  (e: 'input', value: string): void
  (e: 'focus'): void
  (e: 'blur'): void
  (e: 'image-upload', file: File): Promise<string> | void
  (e: 'image-upload-error', error: Error, file: File): void
  (e: 'image-inserted', imageUrl: string): void
  (e: 'submit'): void
  (e: 'word-count-change', count: number): void
}>()

// Refs
const editorRef = ref<HTMLElement>()
const isFocused = ref(false)
const uploadingImages = ref(new Set<string>()) // 跟踪正在上传的图片

// 格式状态跟踪
const formatStates = ref({
  bold: false,
  italic: false,
  underline: false,
  strikeThrough: false,
  orderedList: false,
  unorderedList: false,
  justifyLeft: false,
  justifyCenter: false,
  justifyRight: false,
  justifyFull: false,
  formatBlock: ''
})

// 选中的格式块
const selectedFormatBlock = ref('p')
const selectedFontSize = ref('16px')
const selectedFontFamily = ref('')

// 颜色选择
const currentForeColor = ref('#000000')
const currentBackColor = ref('#ffffff')
const customForeColor = ref('#000000')
const customBackColor = ref('#ffffff')

// 预设颜色
const textColors = [
  '#000000', '#ffffff', '#ff0000', '#00ff00', '#0000ff',
  '#ffff00', '#ff00ff', '#00ffff', '#800000', '#008000',
  '#000080', '#808000', '#800080', '#008080', '#c0c0c0',
  '#808080', '#ff8080', '#80ff80', '#8080ff', '#ffff80'
]

const bgColors = [
  '#ffffff', '#000000', '#ffebee', '#e8f5e9', '#e3f2fd',
  '#fff3e0', '#f3e5f5', '#e0f2f1', '#fce4ec', '#e1f5fe',
  '#fff9c4', '#f1f8e9', '#fff8e1', '#ede7f6', '#e8eaf6'
]

// Dialog states
const imageDialogVisible = ref(false)
const linkDialogVisible = ref(false)
const tableDialogVisible = ref(false)
const codeDialogVisible = ref(false)

// Dialog forms
const imageForm = ref({
  url: '',
  alt: ''
})

const linkForm = ref({
  url: '',
  text: ''
})

const tableForm = ref({
  rows: 3,
  cols: 3
})

const codeForm = ref({
  language: 'javascript',
  code: ''
})

// Computed properties
const computedPlaceholder = computed(() => {
  return props.placeholder || '请输入内容...'
})

const editorStyle = computed(() => {
  return {
    minHeight: typeof props.minHeight === 'number' ? `${props.minHeight}px` : (props.minHeight || '200px'),
    maxHeight: typeof props.maxHeight === 'number' ? `${props.maxHeight}px` : (props.maxHeight || '400px')
  }
})

// 字数统计
const wordCount = computed(() => {
  if (editorRef.value) {
    const text = editorRef.value.textContent || ''
    return text.length
  }
  return 0
})

const showWordCount = computed(() => props.showWordCount ?? false)

// 拖拽状态
const isDragOver = ref(false)

// Watch for external changes to modelValue
watch(() => props.modelValue, (newValue) => {
  if (editorRef.value && newValue !== editorRef.value.innerHTML) {
    editorRef.value.innerHTML = newValue || ''
  }
})

// Methods
const handleInput = () => {
  if (editorRef.value) {
    const value = editorRef.value.innerHTML
    emit('update:modelValue', value)
    emit('input', value)
    emit('word-count-change', wordCount.value)
  }
}

const handleFocus = () => {
  isFocused.value = true
  emit('focus')
  // 获取当前格式状态
  updateFormatStates()
  
  // 监听选择变化以更新格式状态
  document.addEventListener('selectionchange', updateFormatStates)
}

const handleBlur = () => {
  isFocused.value = false
  emit('blur')
  // 移除选择变化监听
  document.removeEventListener('selectionchange', updateFormatStates)
}

// 键盘快捷键处理
const handleKeyDown = (event: KeyboardEvent) => {
  // Ctrl+K: 插入链接
  if (event.ctrlKey && event.key === 'k') {
    event.preventDefault()
    insertLink()
    return
  }
  
  // Ctrl+Shift+I: 插入图片
  if (event.ctrlKey && event.shiftKey && event.key === 'I') {
    event.preventDefault()
    insertImage()
    return
  }
  
  // Ctrl+\: 清除格式
  if (event.ctrlKey && event.key === '\\') {
    event.preventDefault()
    clearFormat()
    return
  }
  
  // Ctrl+Enter: 提交（触发自定义事件）
  if (event.ctrlKey && event.key === 'Enter') {
    event.preventDefault()
    emit('submit')
    return
  }
  
  // Tab: 处理缩进
  if (event.key === 'Tab') {
    event.preventDefault()
    if (event.shiftKey) {
      formatText('outdent')
    } else {
      formatText('indent')
    }
  }
}

// 拖拽处理
const handleDragOver = (event: DragEvent) => {
  event.preventDefault()
  isDragOver.value = true
}

const handleDragLeave = (event: DragEvent) => {
  event.preventDefault()
  // 检查是否真的离开编辑器区域
  const rect = editorRef.value?.getBoundingClientRect()
  if (rect) {
    const x = event.clientX
    const y = event.clientY
    if (x < rect.left || x > rect.right || y < rect.top || y > rect.bottom) {
      isDragOver.value = false
    }
  }
}

const formatText = (command: string, value?: string) => {
  // 保存当前选区
  const selection = window.getSelection()
  const range = selection && selection.rangeCount > 0 ? selection.getRangeAt(0) : null
  
  // 执行格式化命令
  const success = document.execCommand(command, false, value || undefined)
  
  // 重新聚焦并更新状态
  if (editorRef.value) {
    editorRef.value.focus()
    
    // 恢复选区（某些命令可能会改变选区）
    if (selection && range) {
      selection.removeAllRanges()
      selection.addRange(range)
    }
    
    // 更新格式状态
    updateFormatStates()
  }
  
  // 触发输入事件
  handleInput()
  
  return success
}

// 更新格式状态
const updateFormatStates = () => {
  if (!editorRef.value) return
  
  // 检查各种格式状态
  const commands = [
    'bold', 'italic', 'underline', 'strikeThrough', 
    'orderedList', 'unorderedList',
    'justifyLeft', 'justifyCenter', 'justifyRight', 'justifyFull'
  ]
  
  commands.forEach(cmd => {
    try {
      // 确保只有boolean类型的状态才会被赋值
      if (typeof formatStates.value[cmd as keyof typeof formatStates.value] === 'boolean') {
        (formatStates.value[cmd as keyof typeof formatStates.value] as boolean) = 
          document.queryCommandState(cmd)
      }
    } catch (error) {
      // 忽略某些浏览器不支持的命令
      console.warn(`Command ${cmd} not supported:`, error)
    }
  })
  
  // 获取当前格式块
  try {
    const formatBlock = document.queryCommandValue('formatBlock')
    // 移除可能的标签括号（如 '<p>' -> 'p'）
    const cleanBlock = formatBlock.replace(/[<>]/g, '')
    formatStates.value.formatBlock = cleanBlock
    selectedFormatBlock.value = cleanBlock || 'p'
  } catch (error) {
    console.warn('Error querying formatBlock:', error)
  }
}

// 处理格式块变化
const handleFormatBlockChange = (value: string) => {
  // 对于标题等，需要添加尖括号
  formatText('formatBlock', `<${value}>`)
}

// 字体大小变化
const handleFontSizeChange = (value: string) => {
  // 使用 fontsize 命令设置字体大小
  document.execCommand('fontSize', false, '7') // 设置为最大级别
  // 然后通过样式设置实际大小
  const selection = window.getSelection()
  if (selection && selection.rangeCount > 0) {
    const range = selection.getRangeAt(0)
    const fontElements = range.commonAncestorContainer.nodeType === Node.TEXT_NODE
      ? (range.commonAncestorContainer.parentElement?.getElementsByTagName('font') || [])
      : ((range.commonAncestorContainer as Element)?.getElementsByTagName('font') || [])
    
    if (fontElements.length > 0) {
      Array.from(fontElements).forEach((font: any) => {
        font.style.fontSize = value
      })
    } else {
      // 如果没有 font 元素，创建一个 span
      const span = document.createElement('span')
      span.style.fontSize = value
      try {
        const contents = range.extractContents()
        span.appendChild(contents)
        range.insertNode(span)
      } catch (e) {
        // 如果提取失败，直接插入HTML
        document.execCommand('insertHTML', false, `<span style="font-size: ${value}">${selection.toString()}</span>`)
      }
    }
    
    if (editorRef.value) {
      editorRef.value.focus()
      updateFormatStates()
      handleInput()
    }
  }
}

// 字体变化
const handleFontFamilyChange = (value: string) => {
  if (value) {
    document.execCommand('fontName', false, value.split(',')[0])
  } else {
    // 清除字体设置
    const selection = window.getSelection()
    if (selection && selection.rangeCount > 0) {
      const range = selection.getRangeAt(0)
      const contents = range.extractContents()
      const wrapper = document.createElement('span')
      wrapper.appendChild(contents)
      wrapper.style.fontFamily = ''
      range.deleteContents()
      range.insertNode(wrapper)
    }
  }
  
  if (editorRef.value) {
    editorRef.value.focus()
    updateFormatStates()
    handleInput()
  }
}

// 设置文字颜色
const setForeColor = (color: string | null) => {
  if (color) {
    document.execCommand('foreColor', false, color)
    currentForeColor.value = color
    if (editorRef.value) {
      editorRef.value.focus()
      handleInput()
    }
  }
}

// 设置背景颜色
const setBackColor = (color: string | null) => {
  if (color) {
    document.execCommand('backColor', false, color)
    currentBackColor.value = color
    if (editorRef.value) {
      editorRef.value.focus()
      handleInput()
    }
  }
}

// 插入水平分割线
const insertHorizontalRule = () => {
  document.execCommand('insertHorizontalRule', false)
  if (editorRef.value) {
    editorRef.value.focus()
    handleInput()
  }
}

const clearFormat = () => {
  // 先移除格式
  document.execCommand('removeFormat', false, undefined)
  
  // 然后将格式块重置为段落
  document.execCommand('formatBlock', false, '<p>')
  
  if (editorRef.value) {
    editorRef.value.focus()
    updateFormatStates()
  }
  
  handleInput()
}

const insertLink = () => {
  // 获取选中的文本作为默认链接文本
  const selection = window.getSelection()
  if (selection && selection.toString()) {
    linkForm.value.text = selection.toString()
  } else {
    linkForm.value.text = ''
  }
  linkForm.value.url = ''
  linkDialogVisible.value = true
}

const confirmInsertLink = () => {
  if (!linkForm.value.url) {
    ElMessage.warning('请输入链接URL')
    return
  }
  
  // 确保URL有协议
  let url = linkForm.value.url
  if (!url.startsWith('http://') && !url.startsWith('https://')) {
    url = 'http://' + url
  }
  
  const text = linkForm.value.text || url
  
  // 保存当前选区
  const selection = window.getSelection()
  const hasSelection = selection && selection.toString().length > 0
  
  // 创建链接
  document.execCommand('createLink', false, url)
  
  // 如果没有选中文本，需要设置链接文本
  if (!hasSelection) {
    // 查找最近创建的链接元素
    const links = editorRef.value?.getElementsByTagName('a')
    if (links && links.length > 0) {
      const lastLink = links[links.length - 1]
      lastLink.textContent = text
      // 移动光标到链接后面
      const range = document.createRange()
      range.setStartAfter(lastLink)
      range.setEndAfter(lastLink)
      selection?.removeAllRanges()
      selection?.addRange(range)
    }
  } else if (selection && selection.rangeCount > 0) {
    // 修复链接文本
    const range = selection.getRangeAt(0)
    const parent = range.commonAncestorContainer.parentNode as Element | null
    if (parent && parent.tagName === 'A') {
      parent.textContent = text
    }
  }
  
  // 设置链接的target属性为_blank（在新窗口打开）
  const links = editorRef.value?.getElementsByTagName('a')
  if (links && links.length > 0) {
    const lastLink = links[links.length - 1]
    lastLink.target = '_blank'
    lastLink.rel = 'noopener noreferrer'
  }
  
  linkDialogVisible.value = false
  if (editorRef.value) {
    editorRef.value.focus()
    updateFormatStates()
    handleInput()
  }
}

const insertImage = () => {
  imageForm.value.url = ''
  imageForm.value.alt = ''
  imageDialogVisible.value = true
}

const confirmInsertImage = () => {
  if (!imageForm.value.url) {
    ElMessage.warning('请输入图片URL')
    return
  }
  
  // 保存当前选区
  const selection = window.getSelection()
  
  // 插入图片
  document.execCommand('insertImage', false, imageForm.value.url)
  
  // 设置图片属性
  const images = editorRef.value?.getElementsByTagName('img')
  if (images && images.length > 0) {
    const lastImage = images[images.length - 1]
    if (imageForm.value.alt) {
      lastImage.alt = imageForm.value.alt
    }
    // 设置图片样式
    lastImage.style.maxWidth = '100%'
    lastImage.style.height = 'auto'
    lastImage.style.borderRadius = '4px'
    
    // 移动光标到图片后面
    const range = document.createRange()
    range.setStartAfter(lastImage)
    range.setEndAfter(lastImage)
    selection?.removeAllRanges()
    selection?.addRange(range)
  }
  
  imageDialogVisible.value = false
  if (editorRef.value) {
    editorRef.value.focus()
    updateFormatStates()
    handleInput()
  }
}

// 插入表格
const insertTable = () => {
  tableForm.value.rows = 3
  tableForm.value.cols = 3
  tableDialogVisible.value = true
}

// 确认插入表格
const confirmInsertTable = () => {
  const { rows, cols } = tableForm.value
  
  // 生成表格HTML
  let tableHtml = '<table border="1" cellpadding="4" cellspacing="0" style="width: 100%; border-collapse: collapse;"><tbody>'
  
  for (let i = 0; i < rows; i++) {
    tableHtml += '<tr>'
    for (let j = 0; j < cols; j++) {
      // 第一行作为表头
      const cellType = i === 0 ? 'th' : 'td'
      tableHtml += `<${cellType} style="border: 1px solid #dcdfe6; padding: 8px;">${i === 0 ? `表头${j + 1}` : ''}</${cellType}>`
    }
    tableHtml += '</tr>'
  }
  
  tableHtml += '</tbody></table>'
  
  // 插入表格
  document.execCommand('insertHTML', false, tableHtml)
  
  tableDialogVisible.value = false
  if (editorRef.value) {
    editorRef.value.focus()
    updateFormatStates()
    handleInput()
  }
}

// 插入代码块
const insertCode = () => {
  codeForm.value.language = 'javascript'
  codeForm.value.code = ''
  codeDialogVisible.value = true
}

// 确认插入代码块
const confirmInsertCode = () => {
  if (!codeForm.value.code.trim()) {
    ElMessage.warning('请输入代码内容')
    return
  }
  
  // 转义HTML特殊字符
  const escapedCode = codeForm.value.code
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#039;')
    .replace(/\n/g, '<br>')
    .replace(/\s/g, '&nbsp;')
  
  // 生成代码块HTML
  const codeHtml = `
    <pre style="background-color: #f5f7fa; padding: 12px; border-radius: 4px; overflow-x: auto; font-family: Consolas, Monaco, 'Andale Mono', monospace; font-size: 14px; line-height: 1.5;">
      <code class="language-${codeForm.value.language}" style="color: #333;">
        ${escapedCode}
      </code>
    </pre>
  `
  
  // 插入代码块
  document.execCommand('insertHTML', false, codeHtml)
  
  codeDialogVisible.value = false
  if (editorRef.value) {
    editorRef.value.focus()
    updateFormatStates()
    handleInput()
  }
}

// 处理图片粘贴
const handlePaste = async (event: ClipboardEvent) => {
  // 阻止默认粘贴行为
  event.preventDefault()
  
  const clipboardData = event.clipboardData
  if (!clipboardData) return
  
  // 检查是否包含图片
  const items = clipboardData.items
  if (items) {
    for (let i = 0; i < items.length; i++) {
      if (items[i].type.indexOf('image') !== -1) {
        const file = items[i].getAsFile()
        if (file) {
          await processImageFile(file)
        }
        return
      }
    }
  }
  
  // 检查是否有HTML内容（保留富文本格式但清理不需要的样式）
  const html = clipboardData.getData('text/html')
  if (html) {
    // 清理HTML，移除危险标签和样式
    const cleanHtml = sanitizeHtml(html)
    document.execCommand('insertHTML', false, cleanHtml)
    handleInput()
    return
  }
  
  // 如果不是图片或HTML，直接粘贴纯文本内容
  const text = clipboardData.getData('text/plain')
  if (text) {
    document.execCommand('insertText', false, text)
    handleInput()
  }
}

// 处理图片拖拽
const handleDrop = async (event: DragEvent) => {
  event.preventDefault()
  
  const dataTransfer = event.dataTransfer
  if (!dataTransfer) return
  
  // 检查是否拖拽了文件
  if (dataTransfer.files.length > 0) {
    const file = dataTransfer.files[0]
    if (file.type.indexOf('image') !== -1) {
      await processImageFile(file)
    }
  }
}

// 处理图片文件
const processImageFile = async (file: File) => {
  // 验证文件类型
  const acceptTypes = props.imageUploadConfig?.accept || ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
  if (!acceptTypes.includes(file.type)) {
    ElMessage.warning(`不支持的图片类型：${file.type}`)
    return
  }
  
  // 验证文件大小
  const maxSize = props.imageUploadConfig?.maxSize || 5 * 1024 * 1024 // 默认5MB
  if (file.size > maxSize) {
    ElMessage.warning(`图片大小超过限制（最大${formatFileSize(maxSize)}）`)
    return
  }
  
  // 生成临时ID
  const tempId = 'temp-img-' + Date.now() + '-' + Math.random().toString(36).substr(2, 9)
  uploadingImages.value.add(tempId)
  
  try {
    // 先使用DataURL临时显示图片
    const tempUrl = await readFileAsDataURL(file)
    const imageElement = insertTempImage(tempUrl, tempId)
    
    // 检查是否有上传前处理函数
    if (props.imageUploadConfig?.beforeUpload) {
      const result = props.imageUploadConfig.beforeUpload(file)
      let imageUrl: string
      
      if (result instanceof Promise) {
        imageUrl = await result
      } else {
        imageUrl = result
      }
      
      // 替换临时图片为正式图片URL
      replaceTempImage(tempId, imageUrl, imageElement as HTMLImageElement | undefined)
      emit('image-inserted', imageUrl)
    } else {
      // 触发上传事件
      const result = emit('image-upload', file)
      
      // 如果上传返回Promise，等待结果
      if (result instanceof Promise) {
        try {
          const imageUrl = await result
          // 替换临时图片为正式图片URL
          replaceTempImage(tempId, imageUrl, imageElement as HTMLImageElement | undefined)
          emit('image-inserted', imageUrl)
        } catch (error) {
          emit('image-upload-error', error instanceof Error ? error : new Error('图片上传失败'), file)
          removeTempImage(tempId, imageElement as HTMLImageElement | undefined)
        }
      }
    }
  } catch (error) {
    emit('image-upload-error', error instanceof Error ? error : new Error('图片处理失败'), file)
  } finally {
    uploadingImages.value.delete(tempId)
  }
}

// 读取文件为DataURL
const readFileAsDataURL = (file: File): Promise<string> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = () => {
      if (typeof reader.result === 'string') {
        resolve(reader.result)
      } else {
        reject(new Error('文件读取失败'))
      }
    }
    reader.onerror = () => reject(new Error('文件读取失败'))
    reader.readAsDataURL(file)
  })
}

// 插入临时图片
const insertTempImage = (tempUrl: string, tempId: string): HTMLImageElement | null => {
  const selection = window.getSelection()
  if (!selection || selection.rangeCount === 0) return null
  
  const range = selection.getRangeAt(0)
  const image = document.createElement('img')
  image.src = tempUrl
  image.dataset.tempId = tempId
  image.className = 'temp-uploading-image'
  image.style.maxWidth = '100%'
  image.style.opacity = '0.7'
  
  // 添加加载中样式
  const loadingSpan = document.createElement('span')
  loadingSpan.className = 'image-loading-indicator'
  loadingSpan.textContent = '上传中...'
  loadingSpan.style.position = 'absolute'
  loadingSpan.style.background = 'rgba(0, 0, 0, 0.5)'
  loadingSpan.style.color = 'white'
  loadingSpan.style.padding = '4px 8px'
  loadingSpan.style.borderRadius = '4px'
  loadingSpan.style.fontSize = '12px'
  
  const wrapper = document.createElement('span')
  wrapper.style.position = 'relative'
  wrapper.appendChild(image)
  wrapper.appendChild(loadingSpan)
  
  range.deleteContents()
  range.insertNode(wrapper)
  
  // 移动光标到图片后面
  range.setStartAfter(wrapper)
  range.setEndAfter(wrapper)
  selection.removeAllRanges()
  selection.addRange(range)
  
  handleInput()
  return image
}

// 替换临时图片为正式图片
const replaceTempImage = (tempId: string, imageUrl: string, tempImage?: HTMLImageElement) => {
  let image = tempImage
  
  if (!image) {
    image = document.querySelector(`img[data-temp-id="${tempId}"]`) as HTMLImageElement | undefined
  }
  
  if (image) {
    // 更新图片URL
    image.src = imageUrl
    delete image.dataset.tempId
    image.className = image.className.replace('temp-uploading-image', '')
    image.style.opacity = '1'
    image.style.maxWidth = '100%'
    image.style.height = 'auto'
    image.style.borderRadius = '4px'
    
    // 移除加载指示器
    const wrapper = image.parentElement
    if (wrapper) {
      const indicator = wrapper.querySelector('.image-loading-indicator')
      if (indicator) {
        wrapper.removeChild(indicator)
      }
      
      // 如果wrapper只有一个子元素，将图片移到wrapper外部
      if (wrapper.children.length === 1) {
        const parent = wrapper.parentElement
        if (parent) {
          parent.insertBefore(image, wrapper)
          parent.removeChild(wrapper)
        }
      }
    }
    
    handleInput()
  }
}

// 移除临时图片
const removeTempImage = (tempId: string, tempImage?: HTMLImageElement) => {
  let image = tempImage
  
  if (!image) {
    const foundImage = document.querySelector(`img[data-temp-id="${tempId}"]`)
    image = foundImage ? foundImage as HTMLImageElement : undefined
  }
  
  if (image) {
    const wrapper = image.parentElement
    if (wrapper) {
      wrapper.remove()
    } else {
      image.remove()
    }
    handleInput()
  }
}

// 清理HTML内容
const sanitizeHtml = (html: string): string => {
  // 创建临时DOM元素来处理HTML
  const tempDiv = document.createElement('div')
  tempDiv.innerHTML = html
  
  // 移除危险标签
  const dangerousTags = ['script', 'iframe', 'object', 'embed', 'link', 'style']
  dangerousTags.forEach(tag => {
    const elements = tempDiv.getElementsByTagName(tag)
    for (let i = elements.length - 1; i >= 0; i--) {
      elements[i].remove()
    }
  })
  
  // 移除所有标签的事件属性
  const allElements = tempDiv.querySelectorAll('*')
  allElements.forEach(element => {
    for (let i = 0; i < element.attributes.length; i++) {
      const attr = element.attributes[i]
      if (attr.name.startsWith('on')) {
        element.removeAttribute(attr.name)
        i--
      }
    }
  })
  
  // 清理样式，只保留安全的样式属性
  const elementsWithStyle = tempDiv.querySelectorAll('[style]')
  elementsWithStyle.forEach(element => {
    // 这里可以根据需要清理或保留特定的样式
    // 为了简单起见，我们移除所有内联样式
    element.removeAttribute('style')
  })
  
  return tempDiv.innerHTML
}

// 格式化文件大小
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 Bytes'
  
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 清空编辑器内容
const clearContent = () => {
  if (editorRef.value) {
    editorRef.value.innerHTML = ''
    handleInput()
  }
}

// 获取纯文本内容
const getPlainText = (): string => {
  if (editorRef.value) {
    return editorRef.value.textContent || ''
  }
  return ''
}

// 插入HTML内容
const insertHTML = (html: string) => {
  if (editorRef.value) {
    document.execCommand('insertHTML', false, html)
    handleInput()
  }
}

// 暴露方法给父组件
defineExpose({
  clearContent,
  getPlainText,
  insertHTML,
  focus: () => editorRef.value?.focus(),
  // 暴露图片处理方法
  processImageFile,
  // 获取当前选中的HTML
  getSelectedHTML: (): string => {
    const selection = window.getSelection()
    if (!selection || selection.rangeCount === 0) return ''
    
    const range = selection.getRangeAt(0)
    const div = document.createElement('div')
    div.appendChild(range.cloneContents())
    return div.innerHTML
  },
  // 插入图片
  insertImage: (imageUrl: string, alt?: string) => {
    document.execCommand('insertImage', false, imageUrl)
    
    // 设置alt属性和样式
    const images = editorRef.value?.getElementsByTagName('img')
    if (images && images.length > 0) {
      const lastImage = images[images.length - 1]
      if (alt) {
        lastImage.alt = alt
      }
      lastImage.style.maxWidth = '100%'
      lastImage.style.height = 'auto'
      lastImage.style.borderRadius = '4px'
    }
    
    handleInput()
  },
  // 插入表格
  insertTable: (rows: number, cols: number) => {
    tableForm.value.rows = rows
    tableForm.value.cols = cols
    confirmInsertTable()
  },
  // 插入代码块
  insertCodeBlock: (code: string, language: string = 'javascript') => {
    codeForm.value.code = code
    codeForm.value.language = language
    confirmInsertCode()
  },
  // 获取当前格式状态
  getFormatStates: () => {
    updateFormatStates()
    return { ...formatStates.value }
  },
  // 执行格式命令
  execCommand: (command: string, value?: string) => {
    return formatText(command, value)
  }
})

// 初始化
onMounted(async () => {
  await nextTick()
  if (editorRef.value) {
    // 初始化内容
    if (props.modelValue) {
      editorRef.value.innerHTML = props.modelValue
    }
    
    // 设置disabled状态
    if (props.disabled) {
      editorRef.value.contentEditable = 'false'
    }
    
    // 初始化样式
    Object.assign(editorRef.value.style, editorStyle.value)
  }
})
</script>

<style scoped>
.rich-text-editor {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.editor-toolbar {
  background-color: #f5f7fa;
  padding: 8px 12px;
  border-bottom: 1px solid #dcdfe6;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
  min-height: 44px;
}

.toolbar-section {
  display: flex;
  align-items: center;
}

.editor-content {
  flex: 1;
  padding: 16px 20px;
  outline: none;
  overflow-y: auto;
  line-height: 1.8;
  min-height: v-bind('`${minHeight || 200}px`');
  max-height: v-bind('`${maxHeight || 400}px`');
  transition: all 0.3s ease;
  position: relative;
  background-color: #ffffff;
  font-size: 14px;
  color: #303133;
}

.editor-content.is-focused {
  background-color: #fafafa;
}

.editor-content.drag-over {
  background-color: rgba(64, 158, 255, 0.08);
  border: 2px dashed #409eff;
}

.editor-content:focus {
  background-color: #ffffff;
  outline: none;
}

.editor-content::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.editor-content::-webkit-scrollbar-track {
  background: #f5f7fa;
  border-radius: 4px;
}

.editor-content::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 4px;
  transition: background 0.3s;
}

.editor-content::-webkit-scrollbar-thumb:hover {
  background: #909399;
}

.editor-content:empty:before {
  content: attr(data-placeholder);
  color: #c0c4cc;
  pointer-events: none;
}

/* 图片样式 */
.editor-content :deep(img) {
  max-width: 100%;
  height: auto;
  margin: 12px 0;
  border-radius: 4px;
  transition: all 0.3s ease;
  cursor: pointer;
}

.editor-content :deep(img:hover) {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
  transform: translateY(-1px);
}

/* 临时上传中图片样式 */
.editor-content :deep(.temp-uploading-image) {
  opacity: 0.7;
  border: 1px dashed #909399;
  background-color: #f5f7fa;
}

/* 拖拽样式 */
.editor-content.drag-over {
  border-color: #409eff;
  background-color: rgba(64, 158, 255, 0.1);
}

/* 加载指示器样式 */
.editor-content :deep(.image-loading-indicator) {
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% {
    opacity: 0.6;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0.6;
  }
}

/* 表格样式 */
.editor-content :deep(table) {
  width: 100%;
  border-collapse: collapse;
  margin: 16px 0;
  font-size: 14px;
}

.editor-content :deep(table:hover) {
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.1);
}

.editor-content :deep(th),
.editor-content :deep(td) {
  border: 1px solid #dcdfe6;
  padding: 10px 12px;
  text-align: left;
  transition: background-color 0.2s;
}

.editor-content :deep(th) {
  background-color: #f5f7fa;
  font-weight: 600;
  color: #606266;
}

.editor-content :deep(tr:hover td) {
  background-color: #fafafa;
}

/* 列表样式 */
.editor-content :deep(ul),
.editor-content :deep(ol) {
  padding-left: 28px;
  margin: 12px 0;
}

.editor-content :deep(li) {
  margin: 6px 0;
  line-height: 1.8;
}

/* 引用样式 */
.editor-content :deep(blockquote) {
  margin: 16px 0;
  padding: 8px 16px;
  border-left: 4px solid #409eff;
  background-color: #f5f7fa;
  color: #606266;
  font-style: italic;
}

/* 代码块样式 */
.editor-content :deep(pre) {
  margin: 16px 0;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
  overflow-x: auto;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.5;
  border: 1px solid #ebeef5;
}

.editor-content :deep(code) {
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  background-color: #f5f7fa;
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 13px;
  color: #e74c3c;
}

.editor-content :deep(pre code) {
  background-color: transparent;
  padding: 0;
  color: inherit;
}

/* 标题样式 */
.editor-content :deep(h1),
.editor-content :deep(h2),
.editor-content :deep(h3),
.editor-content :deep(h4),
.editor-content :deep(h5),
.editor-content :deep(h6) {
  margin: 16px 0 12px 0;
  font-weight: 600;
  line-height: 1.4;
  color: #303133;
}

.editor-content :deep(h1) {
  font-size: 24px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 8px;
}

.editor-content :deep(h2) {
  font-size: 20px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 6px;
}

.editor-content :deep(h3) {
  font-size: 18px;
}

.editor-content :deep(h4) {
  font-size: 16px;
}

/* 链接样式 */
.editor-content :deep(a) {
  color: #409eff;
  text-decoration: none;
  transition: color 0.3s;
}

.editor-content :deep(a:hover) {
  color: #66b1ff;
  text-decoration: underline;
}

/* 按钮组样式 */
:deep(.el-button-group) {
  display: flex;
  flex-wrap: wrap;
}

:deep(.el-divider--vertical) {
  margin: 0 8px;
  height: 24px;
}

/* 选择框样式 */
:deep(.el-select) {
  margin-right: 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .editor-toolbar {
    padding: 6px;
    gap: 4px;
  }
  
  :deep(.el-button) {
    padding: 4px 8px;
    font-size: 12px;
  }
  
  :deep(.el-select) {
    width: 80px !important;
  }
}
</style>